package se.vgregion.icc.riv.itintegration.monitoring;

import java.lang.reflect.ParameterizedType;
import java.net.URL;

import org.apache.cxf.bus.spring.SpringBusFactory;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

/***
 * Creates an JaxWS proxy to communicate with other components.
 * 
 * @author andan40 & ricra2
 * @param <i>
 */
public abstract class AbstractConsumer<i> {

    private static final String CXF_CONSUMER_CONFIG_FILE = "cxf-consumer-config.xml";

    private i service = null;

    /***
     * Constructor that's creates a service proxy object. 
     * 
     * @param serviceAddress the address that you want to call
     */
    @SuppressWarnings("unchecked")
    public AbstractConsumer(String serviceAddress) {

        Class<i> serviceClass =
            (Class<i>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean();
        proxyFactory.setServiceClass(serviceClass);
        proxyFactory.setAddress(serviceAddress);
        proxyFactory.setBus(new SpringBusFactory().createBus(getCxfConfigFileUrl()));

        service = (i) proxyFactory.create();
    }

    /**
     * Getter of the client side service proxy object.
     * @return the client side service object.
     */
    protected i getService() {
        return service;
    }

    /***
     * Getter for the cxf-config file.
     * 
     * @return the URL for the cxf-config file
     */
    private URL getCxfConfigFileUrl() {
        return AbstractConsumer.class.getClassLoader().getResource(CXF_CONSUMER_CONFIG_FILE);
    }
}
